package com.chen.retrofitdemo.net;

import android.util.JsonReader;
import android.util.Log;

import androidx.lifecycle.LiveData;

import com.chen.retrofitdemo.model.Result;
import com.google.gson.GsonBuilder;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.net.ConnectException;
import java.util.concurrent.atomic.AtomicBoolean;

import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
import retrofit2.Response;


public class LiveDataCallAdapter<R> implements CallAdapter<R, LiveData<R>> {
    private final Type responseType;

    public LiveDataCallAdapter(Type responseType) {
        this.responseType = responseType;
    }

    @Override
    public Type responseType() {
        return responseType;
    }

    @Override
    public LiveData<R> adapt(final Call<R> call) {
        return new LiveData<R>() {
            AtomicBoolean started = new AtomicBoolean(false);

            @Override
            protected void onActive() {
                super.onActive();
                if (started.compareAndSet(false, true)) {
                    call.enqueue(new Callback<R>() {
                        @Override
                        public void onResponse(Call<R> call, Response<R> response) {
                            R body = response.body();
                            String path = call.request().url().encodedPath();
                            Log.e("network","onResponse:"+ path);
                            postValue(body);
                        }

                        @Override
                        public void onFailure(Call<R> call, Throwable throwable) {
                            if (throwable instanceof ConnectException) {
                                Result<String> result=new Result<>();
                                result.setCode(-1);
                                result.setMsg(throwable.getMessage());
                                result.setData("");
                                postValue((R) result);
                            } else {
                                postValue(null);
                            }
                        }
                    });
                }
            }
        };
    }
}
